<template>
    <van-nav-bar title="购物车" fixed @click-left="onBack" />

    <div style="height: 46px;"></div>

    <!-- 复选框组 -->
    <van-checkbox-group v-model="state.checkedArr" v-if="state.CartList.length > 0" ref="checkboxGroup">
        <!-- 侧滑块 -->
        <van-swipe-cell v-for="item in state.CartList" :key="item.id">
            <!-- 商品卡片 -->
            <van-card :price="item.total" :title="item.product.name" class="goods-card">
                <!-- 图片 -->
                <template #thumb>
                    <van-checkbox :name="item.id"></van-checkbox>
                    <img :src="item.product.avatars_cdn[0]" alt="">
                </template>
                <!-- 数量 -->
                <template #num>
                    <van-stepper :max="item.product.stock" @change="onChange(item.id, item.pronum)" v-model="item.pronum"
                        theme="round" button-size="22" disable-input />
                </template>

                <!-- 描述 -->
                <template #desc>
                    <span>商品单价：￥{{ item.price }}</span>
                </template>
            </van-card>
            <!-- 侧滑块 => 向左滑 -->
            <template #right>
                <van-button @click="onDel(item.id)" square text="删除" type="danger" class="delete-button" />
            </template>
        </van-swipe-cell>
    </van-checkbox-group>
    <van-empty v-else description="空空如也" />
    <div style="height: 100px;"></div>

    <van-submit-bar class="cart" :price="state.total" button-text="提交订单" @submit="onSubmit">
        <van-checkbox v-model="state.checked" @click="checkAll">全选</van-checkbox>
    </van-submit-bar>

    <Tab />
</template>

<script setup>
import Tab from 'components/common/Tab.vue'
import { ref, reactive, onMounted, watch } from 'vue'
import { useUserStore } from '@/store/user.js'
import { storeToRefs } from 'pinia'
import { useRouter } from 'vue-router'
import apiList from '@/api'
import resJudge from '@/hooks/res.js'
import { showNotify } from 'vant'

const router = useRouter()
const userStore = useUserStore()
const { userInfo } = storeToRefs(userStore)

const state = reactive({
    checkedArr: [],
    num: 0,
    checked: false,
    CartList: [],
    total: 0
})

const checkboxGroup = ref(null);

//监听商品的选择按钮
watch(
    () => state.checkedArr,
    (newVal) => {
        let total = 0
        if (newVal.length == 0) {
            state.total = 0
        }
        for (let item of state.CartList) {
            if (newVal.includes(item.id)) {
                total += parseFloat(item.total)
            }
        }
        state.total = total * 100
        if (newVal.length == state.CartList.length) {
            state.checked = true
        } else {
            state.checked = false
        }
    }
)

//全选按钮
const checkAll = () => {
    if (state.checkedArr.length != state.CartList.length) {
        checkboxGroup.value.toggleAll(true)
    } else {
        checkboxGroup.value.toggleAll()
    }
}
const onBack = () => history.go(-1)

onMounted(() => {
    getCartData()
})

//请求获取购物车数据
async function getCartData() {
    let result = await apiList.CartIndex({ busid: userInfo.value.id })

    if (result.code === 1) {
        state.CartList = result.data
    }
}

//删除购物车商品
async function onDel(cartid) {
    let data = {
        busid: userInfo.value.id,
        cartid
    }

    let result = await apiList.CartDel(data)

    resJudge(result)

    getCartData()

    state.checkedArr = []

    state.checked = false

}
//改变数量，加减按钮
async function onChange(cartid, pronum) {
    let data = {
        cartid,
        pronum
    }

    let result = await apiList.CartNumUpdate(data)

    if (result.code === 0) {
        showNotify({
            type: 'warning',
            message: result.msg,
            duration: 1500
        })

        return false
    }

    getCartData()

}

//提交订单
function onSubmit() {
    // 把数组转成字符串
    let cartids = state.checkedArr.join(',')
    if (!cartids) {
        showNotify({
            type: 'warning',
            message: '请选择结算的商品',
            duration: 1500
        })

        return false
    }
    router.push({ path: '/order/cart/confirm', query: { cartids,total:state.total } })
    // router.push({ path: '/business/base/index', query: { cartids } })
}
</script>

<style>
.cart {
    bottom: 49px;
}

.goods-card {
    margin: 0;
    background-color: white;
}

.delete-button {
    height: 100%;
}

.van-card__thumb {
    display: flex;
    width: auto;
}

.van-card__thumb img {
    width: 88px;
    margin-left: 10px;
}
</style>